package 两数之和1;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @author 谢阳
 * @version 1.8.0_131
 */
class Solution {
    public static void main(String[] args) {
        int[] arr = {3, 2, 4};
        int[] ints = twoSum(arr, 6);
        System.out.println(Arrays.toString(ints));
    }

    public static int[] twoSum(int[] nums, int target) {
        //int length = nums.length;
        //HashMap<Integer, Integer> map = new HashMap<>();
        //for (int i = 0; i < length; i++) {
        //    int key = target - nums[i];
        //    if (map.containsKey(key)) {
        //        return new int[]{map.get(key), i};
        //    }
        //    map.put(nums[i], i);
        //}
        //return null;

        int right = nums.length - 1;
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        int left = 0;
        while (left <= right) {
            if (hashMap.containsKey(target - nums[left])) {
                return new int[]{left, hashMap.get(target - nums[left])};
            } else {
                hashMap.putIfAbsent(nums[left], left);
            }

            if (hashMap.containsKey(target - nums[right])) {
                return new int[]{right, hashMap.get(target - nums[right])};
            } else {
                hashMap.putIfAbsent(nums[right], right);
            }
            left++;
            right--;
        }
        return new int[2];
    }
}